<?php
/**
 * Created by PhpStorm.
 * User: Edik
 * Date: 2016/2/23
 * Time: 11:29
 */

namespace Admin\Controller;


use Admin\Model\PrivilegeModel;
use Think\Controller;

class AdminBaseController extends Controller
{
    public function __construct(){
        // 先调用父类的构造函数
        parent::__construct();
        // 获取当前管理员的ID
        $adminId = session('a_id');
        // 验证登录
        if(!$adminId){
            redirect(U('Admin/Index/Index'));
        }



        // 取出当前管理员所有的权限
        if($adminId == 1){
            $sql = "SELECT * FROM ed_privilege where level in('1','2') order by id";
        }else{
            $sql = 'SELECT b.*
			  FROM ed_role_privilege a
			   LEFT JOIN ed_privilege b ON a.pri_id=b.id
			   LEFT JOIN ed_member_role c ON a.role_id=c.role_id
			    WHERE c.member_id='.$adminId." and level in('1','2') order by id";
        }
        $db = M();
        $pri = $db->query($sql);


        //传递菜单
        $this->assign('menu',$pri);

        /******************判断菜单ID******************************/
        $menuid = I('get.menuid', false);

        if($menuid == false){
            //如果GET参数中没有,尝试从session中获取
            $menuid = I('session.menuid', false);
        }else{
            //如果GET中有值,放到session中
            session('menuid', $menuid);
        }

        if($menuid){
            $this->assign(array(
                'menupid'   =>  substr($menuid, 0, 2),
                'menuid'    =>  $menuid,
            ));
        }
        /********************判断结束******************************/



        // 验证当前管理员是否有权限访问这个页面
        // 1. 先获取当前管理员将要访问的页面	 - TP带三个常量
        $url = MODULE_NAME .'/'. CONTROLLER_NAME . '/' . ACTION_NAME;
        // 查询数据库判断当前管理员有没有访问这个页面的权限
        $where = 'module_name="'.MODULE_NAME.'" AND controller_name="'.CONTROLLER_NAME.'" AND action_name="'.ACTION_NAME.'"';


        if($adminId == 1){
            $sql = "SELECT COUNT(*) has FROM ed_privilege WHERE  1=1 and ".$where;
        }else{
            $sql = "SELECT COUNT(a.role_id) has
			  FROM ed_role_privilege a
			   LEFT JOIN ed_privilege b ON a.pri_id=b.id
			   LEFT JOIN ed_member_role c ON a.role_id=c.role_id
			    WHERE c.member_id='.$adminId.' AND ".$where;
        }
        $db = M();
        $pri = $db->query($sql);

        // 任何人只要登录了就可以进入后台
        if(CONTROLLER_NAME == 'Home'){
            return TRUE;
        }else if($pri[0]['has'] < 1){
            $this->error('无权访问！');
        }




    }

    public function menu()
    {
        $adminId = session('a_id');
        /********** 取出当前管理员所拥有的前两级的权限 ************/

    }
}